"""
部分informer结果不在本地局域网，需要用几个excel文件来上传
"""
import os
import pandas as pd
from pymongo import MongoClient
from tools.utils import load_config
import yaml


def load_config():
    with open("config.yaml", 'r', encoding='utf-8') as f:
        data = yaml.load(f.read(), yaml.FullLoader)
    print("loading_config ... >>> 读取本地配置")
    return data


def loc_collection(db_name, collection_name, cfg={}):
    if len(cfg) == 0:
        cfg = load_config()
    conn = MongoClient(cfg['mongodb'])
    coll_ = conn[db_name][collection_name]
    return coll_


def load_data():
    dir_name = '../data/informer_pred_data_weekly'
    pths = os.listdir(dir_name)
    pths = [s for s in pths if '20' in s]
    path = f"{dir_name}/{pths[0]}"
    map_data = pd.read_excel(f"{dir_name}/map.xlsx", header=1, index_col=0)
    dic = map_data.iloc[:, 0].to_dict()
    data = pd.read_excel(path, index_col=0)
    data['str_name'] = [dic[s] for s in data['y_name'].to_list()]
    return data, pths[0].replace('.xlsx', '')


def upload_informer_weekly(data):
    li = []
    all_names = data.columns.to_list()
    all_names = [str(s)[:10] if '20' in all_names else s for s in all_names]
    data.columns = all_names
    metric_names = [s for s in all_names if '20' not in str(s)]
    date_names = [s for s in all_names if '20' in str(s)]
    for idx in data.index.to_list():
        dic = data.loc[idx, metric_names].to_dict()
        dic['y_pred'] = data.loc[idx, date_names].to_list()
        dic['t'] = [str(s)[:10] for s in date_names]
        li.append(dic)
    return li


data, coll_name = load_data()
ll = upload_informer_weekly(data)
cfg = load_config()
ss = loc_collection('informer_weekly', coll_name, cfg)
ss.insert_many(ll)
